package com.example.group.network.express_plus_app;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;

import com.android.volley.toolbox.Volley;
import com.example.group.network.express_plus_app.Dao.AppDatabase;
import com.example.group.network.express_plus_app.Dao.UserDao.UserDao;

import com.example.group.network.express_plus_app.bean.MyResponse;
import com.example.group.network.express_plus_app.data.model.LoggedInUser;
import com.example.group.network.express_plus_app.http.MySingleton;
import com.example.group.network.express_plus_app.http.VolleyMultipartRequest;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.widget.imageview.RadiusImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PrivateInfoActivity extends AppCompatActivity implements View.OnClickListener {
    final static int REQUEST_CODE_PICK_IMAGE=0;
    final static String TAG="ReadPhoneAlumActivity";
    UserDao userDao;
    String imagename;
    Bitmap bitmap = null;
    @BindView(R.id.riv_user_face)
    RadiusImageView radiusImageView;
    @BindView(R.id.ly_net_name)
    LinearLayout ly_net_name;
    @BindView(R.id.tv_show_net_name)
    TextView tv_show_net_name;
    private ImageLoader imageLoader;
    String server_ip;
    HashMap<String, String> mInfoMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_private_info);
        ButterKnife.bind(this);
        XUI.initTheme(this);
        server_ip = getApplicationContext().getString(R.string.server_ip);
        setActionBar("个人信息");
        imageLoader= MySingleton.getInstance(getApplicationContext()).getImageLoader();
        userDao=AppDatabase.getsInstance(this).userDao();
        initMyInfo();
        ly_net_name.setOnClickListener(this);
        radiusImageView.setOnClickListener(this);
    }


    /**
     * 吃出使用ImageLoader,ImageLoader比ImageRequest更高效，功能功能更多
     */
    public void initMyInfo(){

        mInfoMap = MainApplication.getInstance().mInfoMap;
        String url=server_ip+"express-user/images/"+mInfoMap.get("user_face");
        ImageLoader.ImageListener listener= ImageLoader.getImageListener(radiusImageView,R.mipmap.ic_launcher,R.mipmap.ic_launcher);
        imageLoader.get(url,listener);//后边也可以添加参数，进行图片压缩，设置填充格式
        tv_show_net_name.setText(mInfoMap.get("net_name"));
    }

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.ly_net_name){
            Intent intent = new Intent(PrivateInfoActivity.this, UpdateNetNameActivity.class);
            startActivity(intent);
        }else if(v.getId()==R.id.riv_user_face){
            getImageFromAlbum();
        }
    }
    protected void getImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ContentResolver resolver = getContentResolver();
        if (requestCode ==REQUEST_CODE_PICK_IMAGE){
            Uri uri = data.getData();
            try {
                //获取压缩图片
                bitmap= MediaStore.Images.Media.getBitmap(resolver,uri);
                radiusImageView.setImageBitmap(bitmap);
                uploadBitmap( bitmap);
                String[] proj = {MediaStore.Images.Media.DATA};
                //好像是Android多媒体数据库的封装接口，具体的看Android文档
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                //按我个人理解 这个是获得用户选择的图片的索引值
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                //将光标移至开头 ，这个很重要，不小心很容易引起越界
                cursor.moveToFirst();
                //最后根据索引值获取图片路径
                String path = cursor.getString(column_index);
                Log.i(TAG,path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public void setActionBar(String title){
        //标题栏设置
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        supportActionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_ios_24);
        supportActionBar.setTitle(title);

    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void uploadBitmap(final Bitmap bitmap) {

        String URL=server_ip+"express-user/user-controller/update-user-face?";

        String token = mInfoMap.get("token");
        String phone = mInfoMap.get("phone");
        Map<String,String> head=new HashMap<>();
        head.put("Authorization","Bearer "+token);
/*        ProgressDialog progressDialog = new ProgressDialog(ReadPhoneAlumActivity.this);
        progressDialog.setMessage("Uploading, please wait...");
        progressDialog.show();*/
        //our custom volley request
        VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
                new Response.Listener<MyResponse>() {
                    @Override
                    public void onResponse(MyResponse response) {
                        Log.i("response",response.toString());
                        if (response.getOk()){
                            LoggedInUser loggedInUser = new LoggedInUser(mInfoMap.get("phone"),mInfoMap.get("net_name"),mInfoMap.get("token"),mInfoMap.get("user_face"),
                                    mInfoMap.get("delivery_address"));
                            loggedInUser.setImagePath(imagename);
                            mInfoMap.replace("user_face",imagename);
                            userDao.updateUserDeliveryAddress(loggedInUser);
                            Toast.makeText(getApplicationContext(), "头像修改成功！", Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {


            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("userPhone",phone);
                return parameters;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> head=new HashMap<>();
                head.put("Authorization","Bearer "+token);
                return head;
            }

            /*
             * Here we are passing image by renaming it with a unique name
             * */
            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                imagename = UUID.randomUUID()+".png";
                params.put("image_file", new DataPart(imagename , getFileDataFromDrawable(bitmap)));
                return params;
            }
        };

        //adding the request to volley
        Volley.newRequestQueue(this).add(volleyMultipartRequest);
    }

    /*
     * The method is taking Bitmap as an argument
     * then it will return the byte[] array for the given bitmap
     * and we will send this array to the server
     * here we are using PNG Compression with 80% quality
     * you can give quality between 0 to 100
     * 0 means worse quality
     * 100 means best quality
     * */
    public byte[] getFileDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }


}